package com.aiobc.business.common.service;

import com.aiobc.business.common.domain.SysDict;
import com.alibaba.fastjson.TypeReference;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * Title:基础缓存
 * <p>Description:{@link Caffeine}</p>
 * @author liqiang on 2020年6月13日
 */
public abstract class BasicCache {
    public static final String LOCAL_BASIC_DICT_TYPE_CODE = "dict:typeCode";//所有基础字典信息，以typeCode作为key，存储结构：Map<String,List<Option>>

    private static final TypeReference<Map<String,List<SysDict>>> optionMapType = new TypeReference<Map<String,List<SysDict>>>(){};

    //基础服务缓存信息
    public static final Cache<String,Object> basicCache = Caffeine.newBuilder().initialCapacity(10).maximumSize(15).build();

    public static void sysDictsLoading(Map<String,List<SysDict>> dicts) {
        basicCache.put(LOCAL_BASIC_DICT_TYPE_CODE,dicts);
    }
    //从缓存中获取字典信息
    public static Map<String,List<SysDict>> getSysDictsWithTypeCode() {
        return getCacheData(optionMapType,LOCAL_BASIC_DICT_TYPE_CODE,() -> new HashMap<>());
    }

    private static <T> T getCacheData(TypeReference<T> typeReference, String cacheKey, Supplier<T> supplier) {
        Object object = basicCache.getIfPresent(cacheKey);
        if (Objects.nonNull(object)) {
            return (T) object;
        }
        T target = supplier.get();
        basicCache.put(cacheKey,target);
        return target;
    }
}
